The canonical example of where a pool is useful, is a game entity firing bullets. If you simply create a new instance of a bullet each time you fire, you will soon run out of memory. To avoid allocating new memory each time, you can reuse bullets that have moved off-screen or have collided with something. There are several implementations that have been posted online such as:
- http://www.xnawiki.com/index.php?title=Generic_Resource_Pool
- http://swampthingtom.blogspot.com/2007/06/generic-pool-collection-class.html
I wanted a simple resource pool which provided the functionality of providing a "new" instance of an object when I needed one. So I created my own; The basic design is that there are only two methods: "New", and "Return". The new method returns a new instance that is ready to use, while the return method adds a previously obtained object back into the pool.
An interesting feature of this pool is that you can control the object initialization logic by providing a simple lambda to the constructor. Any initialization logic (such as resetting "isdead" fields, or resetting positions) can be done there and it will be executed for each new instance.using System; using System.Collections.Generic;
namespace Scurvy { public class Pool<T> where T : class, new() { private Queue<T> queue; private Action<T> newRoutine;
public Pool(int capacity) { this.queue = new Queue<T>(capacity); }
public Pool() { this.queue = new Queue<T>(); }
public Pool(Action<T> newRoutine) : this() { this.newRoutine = newRoutine; }
public int Count { get { return this.queue.Count; } }
public T New() { T item;
item = queue.Count > 0 ? queue.Dequeue() : new T(); if (this.newRoutine != null) this.newRoutine(item);
return item; }
public void Return(T item) { queue.Enqueue(item); } } }
I'd love to get feedback on this class if you end up using it in a project. Thanks!